package com.logos.musicframe.ui.javafx;

import com.logos.musicframe.controller.SongsLikedController;
import com.logos.musicframe.controller.SongsPlaylistController;
import com.logos.musicframe.resp.SongsResp;
import com.logos.musicframe.result.Result;
import com.logos.musicframe.utils.JavaFxMusicPlayer;
import com.logos.musicframe.utils.SpringContextUtil;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author logos
 * date 2025/6/14 15:06
 * @version v1.0
 * @Package com.logos.musicframe.ui.javafx
 */
@Slf4j
public class LikesPageUi {
    
    private SongsLikedController songsLikedController = SpringContextUtil.getBean(SongsLikedController.class);
    private SongsPlaylistController songsPlaylistController = SpringContextUtil.getBean(SongsPlaylistController.class);
    private JavaFxMusicPlayer player;
    
    // 当前选中的歌曲
    private SongsResp currentSong;
    
    // 回调接口，用于通知主UI更新当前歌曲
    private SongSelectedCallback songSelectedCallback;
    
    // 主UI实例，用于调用添加到歌单对话框
    private MainMusicPlayerUi mainUI;
    
    public LikesPageUi(JavaFxMusicPlayer player, SongSelectedCallback songSelectedCallback) {
        this.player = player;
        this.songSelectedCallback = songSelectedCallback;
        
        // 获取主UI实例
        try {
            this.mainUI = SpringContextUtil.getBean(MainMusicPlayerUi.class);
        } catch (Exception e) {
            log.error("获取MainMusicPlayerUi实例失败", e);
        }
    }
    
    public VBox createLikesPage() {
        VBox contentBox = new VBox(15);
        contentBox.setPadding(new Insets(10));

        // 标题
        Label titleLabel = new Label("喜欢");
        titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");
        contentBox.getChildren().add(titleLabel);

        // 统计信息
        HBox statsBox = new HBox(20);
        statsBox.setAlignment(Pos.CENTER_LEFT);
        statsBox.setPadding(new Insets(10, 0, 10, 0));

        Result<List<SongsResp>> result = songsLikedController.getUserLikedSongs();
        List<SongsResp> songsLikedResp;
        if (result.isSuccess()) {
            songsLikedResp = result.getData();
        } else {
            songsLikedResp = new ArrayList<>();
        }

        Label songCount = new Label("歌曲 " + songsLikedResp.size());
        songCount.setStyle("-fx-font-weight: bold;");
        
        statsBox.getChildren().add(songCount);
        contentBox.getChildren().add(statsBox);

        // 操作按钮
        HBox actionBox = new HBox(10);
        actionBox.setAlignment(Pos.CENTER_LEFT);
        actionBox.setPadding(new Insets(0, 0, 15, 0));

        Button playAllButton = new Button("播放全部");
        playAllButton.setStyle("-fx-background-color: #1db954; -fx-text-fill: white; -fx-font-weight: bold; -fx-padding: 8 15;");
        playAllButton.setOnAction(e -> {
            if (!songsLikedResp.isEmpty()) {
                // 播放第一首歌
                currentSong = songsLikedResp.get(0);
                player.play(currentSong.getFilePath());
                if (songSelectedCallback != null) {
                    songSelectedCallback.onSongSelected(currentSong);
                }
                log.info("播放喜欢列表第一首歌: {}", currentSong.getTitle());
                // TODO: 实现播放列表功能，将整个喜欢列表添加到播放队列
            }
        });

        actionBox.getChildren().add(playAllButton);
        contentBox.getChildren().add(actionBox);

        // 创建表格式布局
        GridPane songsGrid = createLikedSongsGrid(songsLikedResp);
        contentBox.getChildren().add(songsGrid);
        
        // 创建滚动面板，将内容容器放入其中
        ScrollPane scrollPane = new ScrollPane(contentBox);
        scrollPane.setFitToWidth(true);
        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
        scrollPane.getStyleClass().add("edge-to-edge");
        scrollPane.setStyle("-fx-background-color: transparent;");
        
        // 创建包含滚动面板的VBox
        VBox likesPage = new VBox();
        likesPage.getChildren().add(scrollPane);
        VBox.setVgrow(scrollPane, Priority.ALWAYS);
        
        return likesPage;
    }
    
    private GridPane createLikedSongsGrid(List<SongsResp> songsLikedResp) {
        GridPane songsGrid = new GridPane();
        songsGrid.setHgap(15);
        songsGrid.setVgap(10);
        songsGrid.setPadding(new Insets(5));
        
        // 添加表头
        Label numberLabel = new Label("#");
        numberLabel.setStyle("-fx-font-weight: bold;");
        songsGrid.add(numberLabel, 0, 0);
        
        Label titleArtistLabel = new Label("歌曲");
        titleArtistLabel.setStyle("-fx-font-weight: bold;");
        songsGrid.add(titleArtistLabel, 1, 0);
        
        Label artistLabel = new Label("歌手");
        artistLabel.setStyle("-fx-font-weight: bold;");
        songsGrid.add(artistLabel, 2, 0);
        
        Label albumLabel = new Label("专辑");
        albumLabel.setStyle("-fx-font-weight: bold;");
        songsGrid.add(albumLabel, 3, 0);
        
        Label durationLabel = new Label("时长");
        durationLabel.setStyle("-fx-font-weight: bold;");
        songsGrid.add(durationLabel, 4, 0);
        
        Label actionLabel = new Label("操作");
        actionLabel.setStyle("-fx-font-weight: bold;");
        songsGrid.add(actionLabel, 5, 0);
        GridPane.setHalignment(actionLabel, javafx.geometry.HPos.CENTER);
        
        // 添加歌曲行
        for (int i = 0; i < songsLikedResp.size(); i++) {
            addLikedSongRow(songsGrid, songsLikedResp.get(i), i);
        }
        
        // 设置列宽
        ColumnConstraints col1 = new ColumnConstraints(30);  // 序号列
        ColumnConstraints col2 = new ColumnConstraints(250); // 歌曲列
        ColumnConstraints col3 = new ColumnConstraints(150); // 歌手列
        ColumnConstraints col4 = new ColumnConstraints(180); // 专辑列
        ColumnConstraints col5 = new ColumnConstraints(60);  // 时长列
        ColumnConstraints col6 = new ColumnConstraints(120);  // 操作列，增加宽度以容纳更多按钮
        songsGrid.getColumnConstraints().addAll(col1, col2, col3, col4, col5, col6);
        
        return songsGrid;
    }
    
    private void addLikedSongRow(GridPane grid, SongsResp song, int index) {
        // 行背景 - 用于悬停效果
        HBox rowBackground = new HBox();
        rowBackground.setPrefHeight(50);
        rowBackground.setPrefWidth(700);
        GridPane.setColumnSpan(rowBackground, 6); // 扩展行背景跨度到6列
        grid.add(rowBackground, 0, index + 1);
        
        // 序号
        Label number = new Label(String.valueOf(index + 1));
        number.setStyle("-fx-text-fill: #808080;");
        grid.add(number, 0, index + 1);
        
        // 歌曲（带封面）
        HBox songBox = new HBox(10);
        songBox.setAlignment(Pos.CENTER_LEFT);
        
        ImageView cover = new ImageView(new Image(song.getPicture(), 40, 40, true, true));
        
        VBox songInfo = new VBox(3);
        Label songTitle = new Label(song.getTitle());
        songTitle.setStyle("-fx-font-weight: bold;");
        songInfo.getChildren().add(songTitle);
        
        songBox.getChildren().addAll(cover, songInfo);
        grid.add(songBox, 1, index + 1);
        
        // 歌手
        Label artist = new Label(song.getArtist());
        artist.setStyle("-fx-text-fill: #404040;");
        grid.add(artist, 2, index + 1);
        
        // 专辑
        Label album = new Label(song.getAlbum());
        album.setStyle("-fx-text-fill: #606060;");
        album.setWrapText(true);
        grid.add(album, 3, index + 1);
        
        // 时长
        Label duration = new Label(formatDuration(song.getDuration()));
        duration.setStyle("-fx-text-fill: #808080;");
        grid.add(duration, 4, index + 1);
        
        // 操作区域（包含喜欢按钮和添加到歌单按钮）
        HBox actionBox = new HBox(10);
        actionBox.setAlignment(Pos.CENTER);
        
        // 喜欢按钮 - 在喜欢列表中默认都是已喜欢状态
        Button likeButton = new Button();
        likeButton.getStyleClass().add("like-button");
        likeButton.setStyle("-fx-background-color: transparent;");
        
        // 设置为已喜欢状态
        song.setIsLiked(true);
        updateLikeButtonAppearance(likeButton, true);
        
        // 添加点击事件
        likeButton.setOnAction(e -> {
            // 在喜欢列表中点击喜欢按钮就是取消喜欢
            toggleLikeSong(likeButton, song, rowBackground, grid);
        });
        
        // 添加到歌单按钮
        Button addToPlaylistButton = new Button();
        addToPlaylistButton.setStyle("-fx-background-color: transparent;");
        ImageView addIcon = new ImageView(new Image("static/add-to-playlist.png", 20, 20, true, true));
        addToPlaylistButton.setGraphic(addIcon);
        addToPlaylistButton.setTooltip(new Tooltip("添加到歌单"));
        
        // 添加点击事件
        addToPlaylistButton.setOnAction(e -> {
            // 调用主UI中的添加到歌单对话框
            if (mainUI != null) {
                mainUI.showAddToPlaylistDialog(song);
            } else {
                log.error("mainUI实例为空，无法调用添加到歌单对话框");
                // 显示错误提示
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("错误");
                alert.setHeaderText(null);
                alert.setContentText("无法添加歌曲到歌单，请稍后再试");
                alert.showAndWait();
            }
        });
        
        actionBox.getChildren().addAll(likeButton, addToPlaylistButton);
        grid.add(actionBox, 5, index + 1);
        
        // 添加鼠标悬停效果和点击事件
        rowBackground.setOnMouseEntered(e -> {
            rowBackground.setStyle("-fx-background-color: rgba(0,0,0,0.05);");
        });
        rowBackground.setOnMouseExited(e -> {
            rowBackground.setStyle("-fx-background-color: transparent;");
        });
        rowBackground.setOnMouseClicked(event -> {
            // 设置当前播放歌曲
            currentSong = song;
            if (songSelectedCallback != null) {
                songSelectedCallback.onSongSelected(currentSong);
            }
            if (event.getClickCount() == 2) {
                log.info("播放歌曲: " + currentSong.getTitle());
                
                // 实际播放歌曲逻辑
                player.play(currentSong.getFilePath());
            }
        });
    }
    
    // 切换歌曲的喜欢状态
    private void toggleLikeSong(Button likeButton, SongsResp song, HBox rowBackground, GridPane grid) {
        // 异步处理取消喜欢操作
        new Thread(() -> {
            try {
                // 在喜欢列表中点击喜欢按钮就是取消喜欢
                Result<Boolean> result = songsLikedController.unlike(song.getId());
                if (result.isSuccess()) {
                    song.setIsLiked(false);
                    
                    // 延迟一点时间后从UI中移除这一行，让用户看到动画效果
                    Platform.runLater(() -> {
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            log.error("延迟移除行失败", e);
                        }
                        
                        // 获取行索引
                        Integer rowIndex = GridPane.getRowIndex(rowBackground);
                        if (rowIndex != null) {
                            // 移除该行的所有组件
                            grid.getChildren().removeIf(node -> 
                                GridPane.getRowIndex(node) != null && 
                                GridPane.getRowIndex(node).equals(rowIndex));
                            
                            // 更新后续行的索引
                            grid.getChildren().forEach(node -> {
                                Integer nodeRowIndex = GridPane.getRowIndex(node);
                                if (nodeRowIndex != null && nodeRowIndex > rowIndex) {
                                    GridPane.setRowIndex(node, nodeRowIndex - 1);
                                }
                            });
                            
                            // 刷新喜欢页面
                            refreshLikesPage();
                        }
                    });
                }
            } catch (Exception e) {
                log.error("取消喜欢歌曲失败", e);
            }
        }).start();
    }
    
    // 刷新喜欢页面
    private void refreshLikesPage() {
        // 这里可以实现一个完整的页面刷新逻辑
        // 但为了简单起见，我们只是记录一下
        log.info("刷新喜欢页面");
    }
    
    // 更新喜欢按钮的外观
    private void updateLikeButtonAppearance(Button likeButton, boolean isLiked) {
        if (isLiked) {
            // 已喜欢状态
            likeButton.setGraphic(new ImageView(new Image("static/heart-filled.png", 20, 20, true, true)));
            likeButton.setTooltip(new Tooltip("取消喜欢"));
        } else {
            // 未喜欢状态
            likeButton.setGraphic(new ImageView(new Image("static/heart-icon.png", 20, 20, true, true)));
            likeButton.setTooltip(new Tooltip("喜欢"));
        }
    }
    
    // 格式化时间为 mm:ss
    private String formatDuration(int seconds) {
        int minutes = seconds / 60;
        int remainingSeconds = seconds % 60;
        return String.format("%02d:%02d", minutes, remainingSeconds);
    }
    
    // 回调接口，用于通知主UI更新当前歌曲
    public interface SongSelectedCallback {
        void onSongSelected(SongsResp song);
    }
}
